import { settings } from '@/services/settings'

const state = {
  siteName: '',
  siteDescription: '',
  icpNumber: '',
  maxVideoSize: 500,
  allowedVideoFormats: ['mp4', 'webm'],
  enableComments: true,
  commentNeedsReview: true,
  commentInterval: 30,
  enableRegistration: true,
  defaultUserRole: 'user',
  defaultUserStatus: 'active',
  videoNeedsReview: true,
  defaultVideoStatus: 'pending',
  enableVideoDownload: false,
  storageType: 'local',
  storageConfig: {},
  emailConfig: {
    host: '',
    port: 587,
    secure: false,
    user: '',
    pass: '',
    from: ''
  },
  enableCache: true,
  cacheExpiration: 3600,
  autoBackup: false,
  backupInterval: 86400,
  maxBackupFiles: 10
}

const mutations = {
  SET_SETTINGS(state, settings) {
    Object.assign(state, settings)
  },
  UPDATE_SETTING(state, { key, value }) {
    state[key] = value
  }
}

const actions = {
  // 获取系统设置
  async fetchSettings({ commit }) {
    try {
      const data = await settings.getSettings()
      commit('SET_SETTINGS', data)
    } catch (error) {
      console.error('获取系统设置失败:', error)
      throw error
    }
  },

  // 更新系统设置
  async updateSettings({ commit }, settingsData) {
    try {
      await settings.updateSettings(settingsData)
      commit('SET_SETTINGS', settingsData)
    } catch (error) {
      console.error('更新系统设置失败:', error)
      throw error
    }
  },

  // 更新单个设置项
  async updateSetting({ commit }, { key, value }) {
    try {
      await settings.updateSettings({ [key]: value })
      commit('UPDATE_SETTING', { key, value })
    } catch (error) {
      console.error('更新设置失败:', error)
      throw error
    }
  }
}

const getters = {
  // 获取完整的网站标题
  siteTitle: state => {
    return state.siteName || '视频网站'
  },

  // 获取允许的视频格式列表
  allowedVideoFormatsText: state => {
    return state.allowedVideoFormats.join(', ').toUpperCase()
  },

  // 获取最大视频大小（带单位）
  maxVideoSizeText: state => {
    return `${state.maxVideoSize}MB`
  },

  // 检查功能是否启用
  isFeatureEnabled: state => feature => {
    switch (feature) {
      case 'comments':
        return state.enableComments
      case 'registration':
        return state.enableRegistration
      case 'videoDownload':
        return state.enableVideoDownload
      case 'cache':
        return state.enableCache
      case 'autoBackup':
        return state.autoBackup
      default:
        return false
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}